package org.patto.main.wechat.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.patto.main.api.impl.entity.SysWechatKeyword;
import org.patto.main.api.impl.mapper.SysKeywordMapper;
import org.patto.main.wechat.builder.TextBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {
    @Autowired
    private SysKeywordMapper sysKeywordMapper;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

//        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
//            //TODO 可以选择将消息保存到本地
//        }
//
//        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
//        try {
//            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
//                && weixinService.getKefuService().kfOnlineList()
//                .getKfOnlineList().size() > 0) {
//                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
//                    .fromUser(wxMessage.getToUser())
//                    .toUser(wxMessage.getFromUser()).build();
//            }
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }

        //TODO 组装回复消息

        QueryWrapper<SysWechatKeyword> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("keyword_name", wxMessage.getContent());
        // 根据用户发送的内容查询db
        SysWechatKeyword sysWechatKeyword = sysKeywordMapper.selectOne(queryWrapper);
        String content = null;
        if (sysWechatKeyword == null) {
            content = "关键字不存在"; // 调用别人接口查询
        } else {
            content = sysWechatKeyword.getKeywordValue();
        }
        return new TextBuilder().build(content, wxMessage, weixinService);

    }

}
